const router = require("koa-router")();
const Mock = require("mockjs");
const JWT = require("jsonwebtoken");
const key = "666666";
const userList = Mock.mock([
  {
    username: "admin",
    password: "admin",
    avator: "@image(100x100, @color, admin)",
    nickname: "管理员用户",
    role: "admin",
  },
  {
    username: "user",
    password: "user",
    avator: "@image(100x100, @color, user)",
    nickname: "普通用户-user",
    role: "user",
  },
  {
    username: "zhangsan",
    password: "zhangsan",
    avator: "@image(100x100, @color, zhangsan)",
    nickname: "普通用户-张三",
    role: "user",
  },
]);

router.post("/login", (ctx) => {
  const { username, password } = ctx.request.body;
  const item = userList.find(
    (v) => v.username === username && v.password === password
  );

  if (item) {
    ctx.body = {
      code: 200,
      message: "登录成功，换用" + item.nickname,
      data: {
        userInfo: item,
        token: JWT.sign(item, key, {
          expiresIn: 60
        }),
      },
    };
  } else {
    ctx.body = {
      code: 400,
      message: "登录失败, 请重新登录",
    };
  }
});

router.get("/user/info", (ctx) => {
  const { token } = ctx.request.query;
  try {
    const user = JWT.verify(token, key);
    console.log(user.exp)
    console.log(Math.floor(new Date().getTime() / 1000))
    if(user.exp > new Date().getTime() / 1000) {
      ctx.body = {
        code: 200,
        message: "ok",
        data: user,
      };
    } else {
      ctx.body = {
        code: 400,
        message: "token 失效！！！",
      };
    }
  
  } catch (error){
    ctx.body = {
      code: 400,
      data: error,
    };
  }
});

module.exports = router;
